Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object

I have a function that grabs data from a local JSON file and renders it. Simple stuff. I do the fetch request within the useEffect hook to fire it only on the first render. Once the data is fetched, it sets it in employees. Once in employees, I use another useEffect to set some other states with data from employees.

  const [employees, setEmployees] = useState<any>([]);

  useEffect(() => {
    fetch("data.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        setEmployees(data["employees"]);
      });
  }, []);

  useEffect(() => {
    console.log(employees)
    /* set some other state */
  }, [employees]);

/*render list of employees*/

My problem is, I can't actually access the properties within employees. When I console.log the contents of employees, this is what I see, an array of objects

[
  {
      "first_name": "John",
      "last_name": "Doe",
  },
  {
    "first_name": "Jane",
    "last_name": "Doe",
  }]

So to access the properties of the object, i've tried this


employees[0]["first_name"]

employees[0]."first_name"

employees[0][first_name]

employees[0].first_name

In the first two, I get this error


TypeError: Cannot read properties of undefined (reading 'first_name')

While in the last 2 I get this error

Cannot find name 'first_name'

If someone could tell me how to properly access my data it would be much appreciated!

Edit: I'm working in Typescript if that changes anything

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this one

const [employees, setEmployees] = useState<any[]>([])

link: How to declare array as any: when using UseState hook?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!